<?php
declare (strict_types = 1);

namespace app\api\controller;

use think\exception\ValidateException;

use app\common\model\{User, Img};
use app\common\validate\{UserValidate};

class UserController extends BaseController
{
    private $userModel;

    public function __construct(User $userModel)
    {
        parent::initialize();
        $this->userModel = $userModel;
    }

    /** 查询用户信息 */
    public function user_info()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 查询用户信息 */
        $user_info = $this->userModel->getFind(['id' => $data['user_id']]);

        if($user_info['code'] != 'ok'){
            $this->error_back($user_info['msg']);
        }

        unset($user_info['data']['password']);

        $this->success_back('ok', $user_info['data']);
    }

    /** 修改头像 */
    public function setAvatar()
    {
        $data = input('');
        $data['avatar'] = request()->file('avatar');

        try{
            validate(UserValidate::class)->scene('setAvatar')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $img = fileUp($data['avatar'], 'avatar');

        $edit_flag = $this->userModel->edit(['id' => $data['user_id'], 'avatar' => $img]);

        if($edit_flag['code'] != 'ok'){
            $this->error_back($edit_flag['msg']);
        }

        $this->success_back('修改成功');
    }

    /** 修改密码 */
    public function setPassword()
    {
        $data = input('');

        try{
            validate(UserValidate::class)->scene('setPassword')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 查询用户信息 */
        $user_info = $this->userModel->getFind(['id' => $data['user_id']], 'password');

        if($user_info['code'] != 'ok'){
            $this->error_back($user_info['msg']);
        }

        if(setPass($data['password_old']) != $user_info['data']['password']){
            $this->error_back('原密码错误');
        }

        $edit_flag = $this->userModel->edit(['id' => $data['user_id'], 'password' => setPass($data['password_new'])]);

        if($edit_flag['code'] != 'ok'){
            $this->error_back($edit_flag['msg']);
        }

        $this->success_back('修改成功');
    }
}